package com.haojiang.mh.remote.ui.dialog

import android.Manifest
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.text.method.ReplacementTransformationMethod
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.fragment.app.FragmentActivity
import com.google.zxing.Result
import com.haojiang.mh.R
import com.haojiang.mh.remote.adapter.ClientBedDialogFragAdapter
import com.haojiang.mh.remote.base.BaseDialogFrag
import com.haojiang.mh.remote.enums.EConnect
import com.haojiang.mh.remote.enums.EStep
import com.haojiang.mh.remote.event.ConnectEvent
import com.haojiang.mh.remote.ui.activity.QrcodeActivity
import com.haojiang.mh.remote.utils.BleUtil
import com.haojiang.mh.remote.utils.BleUtil.Companion.readGroupSurfaceNo
import com.haojiang.mh.remote.utils.BleUtil.Companion.saveGroupInterfaceNo
import com.haojiang.mh.remote.utils.Constant.QRRM
import com.haojiang.mh.remote.utils.KeyboardUtil
import com.haojiang.mh.remote.utils.Util
import com.lx.permission.IPermissionCallback
import com.lx.permission.PermissionManager
import com.tamsiree.rxfeature.scaner.OnRxScanerListener
import kotlinx.android.synthetic.main.frag_dialog_select_group.*
import org.greenrobot.eventbus.EventBus
import java.util.*

class SelectGroupDialogFrag : BaseDialogFrag() {

    /**
     * 伴生函数
     */
    companion object {
        private var GROUP_TYPE = "group_type"
        private var GROUP_ID = "group_id"
        val instance by lazy {
            SelectGroupDialogFrag()
        }

        fun show(fragmentActivity: FragmentActivity, groupType: Int, groupId: Long) {
//        fun show(fragmentActivity: FragmentActivity) {
            val fm = fragmentActivity.supportFragmentManager
            fm.executePendingTransactions()
            fm.beginTransaction().detach(instance)
            fm.beginTransaction().remove(instance)
            instance.arguments = Bundle(bundleOf(GROUP_TYPE to groupType, GROUP_ID to groupId))
            instance.show(fm, SelectGroupDialogFrag::class.java.simpleName)
        }
    }

    private var groupType = EConnect.CONNECT_SINGLE.data
    private var groupId = 0L

    val clientBedDialogFragAdapter by lazy {
        ClientBedDialogFragAdapter()
    }


    private val onClickListener = object : View.OnClickListener {
        override fun onClick(v: View?) {
            if (v != null) {
                when (v.id) {
                    R.id.tvConfirm -> {
                        val interfaceNo = etSurface.text.toString().trim()
                        if (interfaceNo.length != 4) {
                            showToast(getString(R.string.m_enter_4bit_interface_no))
                        } else {
                            searchInterface(interfaceNo)
                        }
                    }
                    R.id.ivClose -> {
                        dismiss()
                    }
                }
            }
        }
    }


    private val mIPermissionCallback = IPermissionCallback {
        QrcodeActivity.setScanerListener(onRxScanerListener)
        scanQrcode()
    }

    override fun onSubCreate(savedInstanceState: Bundle?) {
        setStyle(STYLE_NO_TITLE, R.style.fragment_dialog)
        groupType = arguments!!.getInt(GROUP_TYPE)
        groupId = arguments!!.getLong(GROUP_ID)
    }

    override fun onSubCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.frag_dialog_select_group, container, false)
    }

    override fun onSubViewCreated(view: View, savedInstanceState: Bundle?) {
        dialog!!.setCancelable(true) //是否可以点击取消
        dialog!!.setCanceledOnTouchOutside(false) //dialog外面是否可以点击

        val params = dialog!!.window!!.attributes
        val context = context
        context?.let {
            //            params.width = (Util.getScreenWidth(context) * 0.7f).toInt()
            params.width = LinearLayout.LayoutParams.WRAP_CONTENT
            params.height = LinearLayout.LayoutParams.WRAP_CONTENT
            params.gravity = Gravity.CENTER
            //高度自己定义
            dialog!!.window!!.setLayout(params.width, params.height)
        }
    }


    override fun onSubActivityCreated(savedInstanceState: Bundle?) {

//        rvInterface.layoutManager = LinearLayoutManager(context)
//        rvInterface.adapter = clientBedDialogFragAdapter


        ivQrcode.setOnClickListener(View.OnClickListener {
            context?.let {
                if (!Util.checkBleStatus(it)) {
                    return@OnClickListener
                }
            }
            PermissionManager.getInstance().setIPermissionCallback(mIPermissionCallback, 0)
            PermissionManager.getInstance().requestPermission(
                context,
                arrayOf(
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.CAMERA,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                )
            )
        })

        tvConfirm.setOnClickListener(onClickListener)
        ivClose.setOnClickListener(onClickListener)

        etSurface.setTransformationMethod(object : ReplacementTransformationMethod() {
            override fun getOriginal(): CharArray {
                return charArrayOf(
                    'a',
                    'b',
                    'c',
                    'd',
                    'e',
                    'f',
                    'g',
                    'h',
                    'i',
                    'j',
                    'k',
                    'l',
                    'm',
                    'n',
                    'o',
                    'p',
                    'q',
                    'r',
                    's',
                    't',
                    'u',
                    'v',
                    'w',
                    'x',
                    'y',
                    'z'
                )
            }

            override fun getReplacement(): CharArray {
                return charArrayOf(
                    'A',
                    'B',
                    'C',
                    'D',
                    'E',
                    'F',
                    'G',
                    'H',
                    'I',
                    'J',
                    'K',
                    'L',
                    'M',
                    'N',
                    'O',
                    'P',
                    'Q',
                    'R',
                    'S',
                    'T',
                    'U',
                    'V',
                    'W',
                    'X',
                    'Y',
                    'Z'
                )
            }
        })

        etSurface.setOnEditorActionListener(TextView.OnEditorActionListener { v, actionId, event ->
            //当actionId == XX_SEND 或者 XX_DONE时都触发
            //或者event.getKeyCode == ENTER 且 event.getAction == ACTION_DOWN时也触发
            //注意，这是一定要判断event != null。因为在某些输入法上会返回null。
            //                if (actionId == EditorInfo.IME_ACTION_SEND
            //                        || actionId == EditorInfo.IME_ACTION_DONE
            //                        || (event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction())) {
            if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
                KeyboardUtil.hideKeyboard(etSurface)
                //处理事件
            }
            false
        })

        initSurfaceNo()                                                                  //设置界面编号
    }

    private fun initSurfaceNo() {
        val surfaceNo = readGroupSurfaceNo(groupId)
        if (TextUtils.isEmpty(surfaceNo)) {
            etSurface.setText(null)
        } else {
            etSurface.setText(surfaceNo)
        }
    }


    private val onRxScanerListener = object : OnRxScanerListener {
        override fun onSuccess(type: String?, result: Result?) {
            result?.let {
                val interfaceNo = result.text.trim()
                if (interfaceNo.length < 4) {
                    showToast(getString(R.string.m_interface_not_exist))
                } else {
                    searchInterface(interfaceNo)
                }
            }
        }

        override fun onFail(type: String?, message: String?) {
        }
    }

    private fun searchInterface(surfaceNo: String) {
//        val funList = SurfaceKey.keyMap.get(surfaceNo.substring(0, 4).toUpperCase(Locale.ROOT))
//        if (funList == null || surfaceNo.equals(QRRM, ignoreCase = true)) {
        if (!BleUtil.isSurfaceExist(surfaceNo) || surfaceNo.equals(QRRM, ignoreCase = true)) {
            showToast(getString(R.string.m_interface_not_exist))
            return
        } else {
            saveGroupInterfaceNo(groupId, surfaceNo)
            instance.dialog!!.dismiss()
//            devConnects(context!!, lastBleDeviceList)   //连接蓝牙设备
//            EventBus.getDefault().post(FunctionEvent(funList))
//            val bleDeviceList = ArrayList<BleRssiDevice>()
//            lastBleDeviceList.forEach {
//                bleDeviceList.add(it)
//            }

            EventBus.getDefault()
                .post(ConnectEvent(EStep.STEP_SELECT_INTERFACE.data, groupType, groupId))

        }
    }

    override fun initDestroy() {
    }


    private fun scanQrcode() {
        startActivity(Intent(activity, QrcodeActivity::class.java))
    }
}